package com.syh.jn.scm.service.impl.upstream.finance;

import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.upstream.entity.finance.UpReceiptBill;
import com.syh.jn.scm.domain.upstream.event.UpReceiptBillEvent;
import com.syh.jn.scm.domain.upstream.repository.finance.UpReceiptBillRepository;
import com.syh.jn.scm.dto.upstream.finance.UpReceiptBillVo;
import com.syh.jn.scm.service.api.upstream.finance.UpReceiptBillService;
import com.syh.jn.scm.service.api.upstream.finance.enums.UpReceiptBillEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UpReceiptBillServiceImpl extends AbstractServiceImpl<Object, Object, UpReceiptBillVo, UpReceiptBill, Long> implements UpReceiptBillService {
  @Autowired
  private UpReceiptBillRepository upReceiptBillRepositoryImpl;

  @Override
  protected AggregateRepository<UpReceiptBill, Long> getAggregateRepository() {
    return upReceiptBillRepositoryImpl;
  }

  /**
   * 确认到账
   *
   * @param id
   * @return
   */
  @Override
  public void confirmState(Long id) {
    UpReceiptBill receiptBill = upReceiptBillRepositoryImpl.getById(id);
    receiptBill.confirmState();
    upReceiptBillRepositoryImpl.update(receiptBill);
    //设置对账单的到账金额
    //发送事件消息
    if (receiptBill.getLockStatus().equals(UpReceiptBillEnum.LOCK.getStatus())) {
      this.publicEvent(UpReceiptBillEvent.upReceiptBillLock(new Object[]{receiptBill}));
    }
  }

  /**
   * 上游取消到账
   *
   * @param id
   */
  @Override
  public void cancel(Long id) {
    UpReceiptBill receiptBill = upReceiptBillRepositoryImpl.getById(id);
    receiptBill.cancel();
    upReceiptBillRepositoryImpl.update(receiptBill);

    //设置对账单的到账金额
    //发送事件消息(未锁定状态和已付款)
    if (receiptBill.getLockStatus().equals(UpReceiptBillEnum.UNLOCK.getStatus()) && receiptBill.getReceiptState().equals(UpReceiptBillEnum.OTHERPARTY_CONFIRM.getStatus())) {
      this.publicEvent(UpReceiptBillEvent.upReceiptBillUnlock(new Object[]{receiptBill}));
    }
  }
}
